package com.thx.org.action;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.ExtendPropertyAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.ComplexPropertyPreFilter;
import com.thx.common.web.ActionResult;
import com.thx.log.LogUtil;
import com.thx.org.model.Company;
import com.thx.org.model.Department;
import com.thx.org.service.CompanyManager;
import com.thx.org.service.DepartmentManager;
import com.thx.user.util.ModuleConstant;
import com.thx.user.util.PinyinUtils;

/**
 *
 * 建立日期 : 2014年4月24日 下午4:11:49<br>
 * 作者 : shiyan<br>
 * 模块 : <br>
 * 描述 :部门action <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 */
@Namespace("/user")
@Action(value = "dept", results = {@Result(name = "tree", location = "/pages/system/org/tree.jsp"),
    @Result(name = "input", location = "/pages/system/org/input.jsp"),
    @Result(name = "json", type = "json", params = {"root", "result"})})
@Controller
@Scope("prototype")
public class DepartmentAction extends ExtendPropertyAction<Department> {

  private static final long serialVersionUID = 1L;

  protected static final String DRAG_INNER = "inner";
  protected static final String DRAG_PREV = "prev";
  protected static final String DRAG_NEXT = "next";

  protected String treeNodes;

  @Autowired
  protected DepartmentManager departmentMgr;

  @Autowired
  protected CompanyManager companyMgr;

  protected boolean isAdd;// --是否是添加部门

  protected String depId;// 拖拽时目标部门的ID
  protected String type;// 拖拽时的相对位置 inner prev next
  protected boolean isCom;// 目标节点是否是企业
  protected String depName;// 被拖拽的部门名称

  private String parentId;// 父部门id


  protected String parentFullName;// 父部门的全路径

  protected String callback;

  protected boolean deleteFlag;

  public String treeList() {
    treeNodes = getDeptJson();
    return "tree";
  }

  public void treeJson() {
    try {
      writeJson(getDeptJson());
    } catch (IOException e) {
      logger.error("", e);
    }
  }

  protected String getDeptJson() {
    try {
      String comId = AppContext.getCurrentComId();
      Company company = companyMgr.get(comId);
      Department root = new Department();
      root.setDepId(comId);
      root.setDepName(company.getComName());
      root.setFullName(company.getComName());
      // --获得该企业的一级部门
      List<Department> depts = departmentMgr.getByParentId(null);

      root.setChildren(depts);
      for (Department d : depts) {
        getChildrenDep(d);
      }
      ComplexPropertyPreFilter filter = new ComplexPropertyPreFilter();
      filter.setIncludes(new HashMap<Class<?>, String[]>() {
        private static final long serialVersionUID = -8411128674046835592L;
        {
          put(Department.class, new String[] {"depId", "depName", "fullName", "children"});
        }
      });
      return com.alibaba.fastjson.JSON.toJSONString(root, filter);
    } catch (Exception e) {
      logger.error("", e);
    }
    return null;
  }

  protected void getChildrenDep(Department dep) {
    List<Department> children = departmentMgr.getByParentId(dep.getDepId());
    if (children != null && children.size() > 0) {
      dep.setChildren(children);
      for (Department child : children) {
        getChildrenDep(child);
      }
    }
  }

  protected void doInput() throws Exception {
    if (isAdd) {
      entity.setParentId(parentId);
      if (StringUtils.isBlank(parentId)) {
        String comId = AppContext.getCurrentComId();
        parentFullName = companyMgr.get(comId).getComName();
      } else {
        parentFullName = departmentMgr.get(parentId).getFullName();
      }
    } else {
      if (StringUtils.isNotBlank(id)) {
        entity = departmentMgr.get(id);
        if (entity == null) {
          setResult(ActionResult.FAIL, "要修改的记录不存在！！！");
        } else {
          // modify Xuejw 修改组织节点时 初始化parentFullName
          parentFullName = entity.getFullName();
          if (StringUtils.isNotBlank(parentFullName) && parentFullName.lastIndexOf("/") > 0) {
            parentFullName = parentFullName.substring(0, parentFullName.lastIndexOf("/"));
          }
        }
      } else {
        setResult(ActionResult.FAIL, "ID为空！！！！");
      }
    }
  }

  public void checkName() {
    try {
      String pid = entity.getParentId();
      if (StringUtils.isBlank(pid)) {
        pid = null;
      }
      // --同级部门是否有重复
      Department dep = departmentMgr.findByName(StringUtils.strip(entity.getDepName()), pid);
      if (dep == null)
        writeJson("true");
      else {
        if (StringUtils.isNotBlank(id) && id.equals(dep.getDepId())) {
          // --修改时用户名和原来的可以保持一致
          writeJson("true");
        } else {
          writeJson("false");
        }
      }

    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  public void checkFullName() {
    try {
      Department dep = departmentMgr.findByFullName(StringUtils.strip(entity.getFullName()));
      if (dep == null)
        writeJson("true");
      else {
        if (StringUtils.isNotBlank(id) && id.equals(dep.getDepId())) {
          writeJson("true");
        } else {
          writeJson("false");
        }
      }

    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  protected void doSave() {
    try {
      if (StringUtils.isBlank(id)) {
        entity.setDepId(null);
        if (StringUtils.isBlank(entity.getParentId())) {
          entity.setParentId(null);
        }
        List<Department> deps = departmentMgr.getByParentId(entity.getParentId());
        int order = 0;
        if (deps != null && deps.size() > 0) {
          order = deps.get(deps.size() - 1).getOrderSeq() + 1;
        }
        entity.setOrderSeq(order);
        String comId = AppContext.getCurrentComId();
        entity.setComId(comId);
        entity.setDeleted("0");
        entity.setCreatTime(new Date());
        entity.setFullName(StringUtils.strip(entity.getFullName()));
        entity.setDepName(StringUtils.strip(entity.getDepName()));
        entity.setPinyin(PinyinUtils.getAlpha(StringUtils.strip(entity.getDepName())));
        departmentMgr.save(entity);
        setResult(ActionResult.SUCCESS, "添加成功！");
        LogUtil.log(ModuleConstant.ORG_MANAGER, LogUtil.ACTION_ADD, LogUtil.RESULT_SUCCESS, "添加部门");
      } else {
        Department dep = departmentMgr.get(id);
        dep.setDepName(StringUtils.strip(entity.getDepName()));
        entity.setPinyin(PinyinUtils.getAlpha(StringUtils.strip(entity.getDepName())));
        dep.setFullName(StringUtils.strip(entity.getFullName()));
        if (StringUtils.isBlank(dep.getFullName())) {
          dep.setFullName(StringUtils.strip(dep.getDepName()));
        }
        dep.setChangeTime(new Date());
        departmentMgr.save(dep);
        setResult(ActionResult.SUCCESS, "修改成功！");
        LogUtil.log(ModuleConstant.ORG_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS,
            "修改部门信息");
      }
    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
      logger.error(e.getMessage(), e);
    }
  }

  protected void doDelMulti() {
    try {
      if (StringUtils.isNotBlank(id)) {
        if (!departmentMgr.recursiveDelete(id, deleteFlag)) {
          setResult(ActionResult.FAIL, "有子部门或关联的数据不能删除！");
        } else {
          setResult(ActionResult.SUCCESS, "删除成功！");
          LogUtil.log(ModuleConstant.ORG_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS,
              "删除部门");
        }
      } else {
        setResult(ActionResult.FAIL, "ID不能为空！");
      }
    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }

  }

  public void toModify() {
    boolean flag = true;
    try {
      if (isCom && !type.equals(DRAG_INNER)) {
        flag = false;
      }
      if (flag) {
        String dId = "";
        if (type.equals(DRAG_INNER)) {
          if (isCom) {
            dId = null;
          } else {
            dId = depId;
          }
        } else {
          Department dep = departmentMgr.get(depId);
          dId = dep.getParentId();
        }
        List<Department> depts = departmentMgr.getByParentId(dId);
        for (Department d : depts) {
          if (d.getDepName().equals(depName)) {
            if (StringUtils.isNotBlank(id) && !id.equals(d.getDepId())) {
              flag = false;
            }
          }
        }
      }
      writeJson(String.valueOf(flag));
    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  public String modify() {
    try {
      String dId = "";
      String dFullName = "";
      int order = 0;
      if (type.equals(DRAG_INNER)) {
        if (isCom) {
          dId = null;
        } else {
          dId = depId;
        }
        List<Department> deps = departmentMgr.getByParentId(dId);
        if (deps != null && deps.size() > 0) {
          order = deps.get(deps.size() - 1).getOrderSeq() + 1;
        }
        Department dep = departmentMgr.get(depId);
        dFullName = dep.getFullName();
      } else {
        // 目标父部门
        Department dep = departmentMgr.get(depId);
        dId = dep.getParentId();
        dFullName = dep.getFullName();
        List<Department> deps = departmentMgr.getByParentId(dId, dep.getOrderSeq());
        int i = 0;
        if (type.equals(DRAG_PREV)) {
          order = dep.getOrderSeq();
        } else if (type.equals(DRAG_NEXT)) {
          i = 1;
          order = dep.getOrderSeq() + 1;
        }
        for (int j = i; j < deps.size(); j++) {
          Department d = deps.get(j);
          d.setOrderSeq(d.getOrderSeq() + 1);
          departmentMgr.save(d);
        }
      }
      // 当前部门
      Department dept = departmentMgr.get(id);
      dept.setParentId(dId);
      dept.setFullName(dFullName + "/" + dept.getDepName());
      dept.setOrderSeq(order);
      departmentMgr.save(dept);
      setResult(ActionResult.SUCCESS, "修改成功！");
      LogUtil.log(ModuleConstant.ORG_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS,
          "修改部门层级关系");
    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
    return JSON;
  }

  public String getTreeNodes() {
    return treeNodes;
  }

  public void setTreeNodes(String treeNodes) {
    this.treeNodes = treeNodes;
  }

  public DepartmentManager getDepartmentMgr() {
    return departmentMgr;
  }

  public void setDepartmentMgr(DepartmentManager departmentMgr) {
    this.departmentMgr = departmentMgr;
  }

  public CompanyManager getCompanyMgr() {
    return companyMgr;
  }

  public void setCompanyMgr(CompanyManager companyMgr) {
    this.companyMgr = companyMgr;
  }

  public boolean getIsAdd() {
    return isAdd;
  }

  public void setIsAdd(boolean isAdd) {
    this.isAdd = isAdd;
  }

  public String getDepId() {
    return depId;
  }

  public void setDepId(String depId) {
    this.depId = depId;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public boolean getIsCom() {
    return isCom;
  }

  public void setIsCom(boolean isCom) {
    this.isCom = isCom;
  }

  public String getDepName() {
    return depName;
  }

  public void setDepName(String depName) {
    this.depName = depName;
  }

  public String getCallback() {
    return callback;
  }

  public void setCallback(String callback) {
    this.callback = callback;
  }

  public boolean getDeleteFlag() {
    return deleteFlag;
  }

  public void setDeleteFlag(boolean deleteFlag) {
    this.deleteFlag = deleteFlag;
  }

  public String getParentFullName() {
    return parentFullName;
  }

  public void setParentFullName(String parentFullName) {
    this.parentFullName = parentFullName;
  }

  public String getParentId() {
    return parentId;
  }

  public void setParentId(String parentId) {
    this.parentId = parentId;
  }
}
